<script setup lang="ts">
import { useCounter } from '../composables/useCounter'
import { useFetch } from '../composables/useFetch'
import { useLocalStorage } from '../composables/useLocalStorage'

// 使用计数器
const { count, increment, decrement, reset } = useCounter(0)

// 使用数据获取
interface Todo {
  id: number
  title: string
  completed: boolean
}

const { data: todos, error, loading, fetchData } = useFetch<Todo[]>(
  'https://jsonplaceholder.typicode.com/todos'
)

// 使用本地存储
const username = useLocalStorage('username', '')
</script>

<template>
  <div class="composables-demo">
    <h2>组合式函数示例</h2>

    <section>
      <h3>1. useCounter</h3>
      <div class="counter">
        <button @click="decrement">-</button>
        <span>{{ count }}</span>
        <button @click="increment">+</button>
        <button @click="reset">重置</button>
      </div>
    </section>

    <section>
      <h3>2. useFetch</h3>
      <div class="fetch-demo">
        <button @click="fetchData" :disabled="loading">
          {{ loading ? '加载中...' : '获取数据' }}
        </button>
        
        <div v-if="error" class="error">
          {{ error.message }}
        </div>
        
        <div v-else-if="todos" class="todos">
          <div v-for="todo in todos.slice(0, 5)" :key="todo.id" class="todo">
            <input type="checkbox" :checked="todo.completed" disabled>
            <span>{{ todo.title }}</span>
          </div>
        </div>
      </div>
    </section>

    <section>
      <h3>3. useLocalStorage</h3>
      <div class="storage-demo">
        <input 
          v-model="username" 
          placeholder="输入用户名（将保存到localStorage）"
        >
        <p>保存的用户名: {{ username || '无' }}</p>
      </div>
    </section>
  </div>
</template>

<style scoped>
.composables-demo {
  padding: 20px;
}

section {
  margin: 20px 0;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.counter {
  display: flex;
  align-items: center;
  gap: 10px;
}

.counter button {
  padding: 5px 15px;
}

.fetch-demo {
  margin: 10px 0;
}

.todos {
  margin-top: 10px;
}

.todo {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 5px 0;
}

.error {
  color: red;
  margin-top: 10px;
}

.storage-demo input {
  width: 300px;
  padding: 5px;
  margin-bottom: 10px;
}
</style>